<?php

namespace app\queue\redis;

use app\api\logic\OrderLogic;
use app\model\order\Order;
use Exception;
use support\constants\LockKey;
use support\constants\QueueKey;
use support\Log;
use support\utils\LockUtil;
use support\utils\Time;
use think\facade\Db;
use Webman\RedisQueue\Consumer;

class CloseOrder implements Consumer
{
    // 要消费的队列名
    public $queue = QueueKey::CLOSE_ORDER;

    // 连接名，对应 plugin/webman/redis-queue/redis.php 里的连接`
    public $connection = 'default';

    // 消费
    public function consume($data)
    {
        Db::transaction(function () use ($data) {
            $key = LockKey::ORDER_ACTION . $data['order_no'];
            $res = LockUtil::lock($key, function () use ($data) {
                $order = Order::where(['order_no' => $data['order_no']])->field([
                    'pay_status',
                    'status',
                ])
                    ->find();

                if ($order['status'] !== Order::STATUS_WAIT_PAID || $order['pay_status'] !== Order::PAY_STATUS_WAIT) {
                    Log::info("订单关闭操作:[{$data['order_no']}]状态已修改");
                    return;
                }
                $logic = new OrderLogic();
                $logic->closeOrderOperation($data['order_no'], [
                    'status' => Order::STATUS_CLOSE,
                    'close_time' => Time::now(),
                ]);
            });
            if (!$res) {
                Log::info("订单关闭操作:[{$data['order_no']}]支付关闭操作抢锁失败");
                throw new Exception("订单[{$data['order_no']}]支付关闭操作抢锁失败");
            }
        });
    }

}
